﻿using System.Collections.Generic;
using VIT.DataTransferObjects.Presentation;

namespace VIT.BusinessLogicLayer
{
    using System.Linq;
    using VIT.DataAccessLayer;
    using VIT.Library;

    public class TemplateBLL : BLLBase
    {
        private readonly ITemplateDAL _templateDAL;

        private readonly string _domainStore;
        private readonly string _imageTemplateDetailPath;
        private readonly string _imageTemplateThumbPath;

        #region Constructor

        public TemplateBLL(string connectionString = "")
            : base(connectionString)
        {
            this._templateDAL = new TemplateDAL(this.DatabaseFactory);

            this._domainStore = SettingsManager.AppSettings.DomainStore;
            this._imageTemplateDetailPath = SettingsManager.AppSettings.TemplateImageDetailPath;
            this._imageTemplateThumbPath = SettingsManager.AppSettings.TemplateImageThumbPath;
        }
        #endregion

        public string GetImageByTemplateName(string TemplateName)
        {
            var query = this._templateDAL.GetAll()
                .Where(e => e.IsPublished && e.HasDeleted == false)
                .Where(e => e.TemplateName == TemplateName)
                .Select(e => e.ImageName);

            var data = query.FirstOrDefault();
            if (data != null) data = this.VirtualPath(this._imageTemplateDetailPath, data);

            return data;
        }

        public IList<TemplateDto> GetAll(out int totalPage, int skip = 0, int take = 0)
        {
            var obj = this._templateDAL.GetAll()
                .Where(c => c.HasDeleted == false && c.IsPublished)
                .Select(o => new TemplateDto
                {
                    TemplateName = o.TemplateName,
                    ImageName = o.ImageName,
                    IsPublic = o.IsPublic
                });

            totalPage = obj.Count();

            obj = obj.OrderByDescending(o => o.TemplateName);
            if (skip > 0) obj = obj.Skip(skip);
            if (take > 0) obj = obj.Take(take);

            var result = obj.ToList();

            foreach (var dto in result)
            {
                dto.ImageDetailPath = this.VirtualPath(this._imageTemplateDetailPath, dto.ImageName);
                dto.ImageThumbPath = this.VirtualPath(this._imageTemplateThumbPath, dto.ImageName);
            }

            return result;
        }

        private string VirtualPath(string folderPath, string fileName)
        {
            return string.IsNullOrEmpty(fileName) ? string.Empty : string.Format("{0}{1}{2}", this._domainStore, folderPath, fileName);
        }
    }
}
